import axios from 'axios';
// let baseURL = process.env.apiUrl;
import { Toast,Notify } from 'vant'
import cacheTool from './cache.js'

//  创建axios实例
const service = axios.create({
  baseURL: '/fsdata', // api的base_url
  timeout: 100 * 1000, // 请求超时时间
});
// 加载laoding
let loading: any;
function endLoading() {
  //使用Element loading-close 方法
}

service.interceptors.request.use(
  (config: any) => {
    //token验证
    // if (config.url.indexOf('get/token') === -1) {
    //   config.headers.common['Authorization'] = `Bearer ${localStorage.token}`;
    // }
    return config;
  },
  error => {
    //请求错误处理
    Promise.reject(error);
  },
);

//  response拦截器
service.interceptors.response.use(
  (response: any) => {
    //成功请求到数据
    const { status, data } = response
    const { code, msg } = data
    if (status === 200) {   // http状态码
      if (code === 200) {   // 后台返回code码
        return Promise.resolve(data)
      } else {
        Notify(msg)
        return false;
      }
    }
  },
  error => {
    Notify('服务器内部错误')
    return Promise.reject(error);
  },
);

// 配置缓存请求api,用于缓存get和post请求数据,
const cacheRequest = cacheTool(service, {
  cacheTime: 5, //缓存周期 默认是5s 单位秒
  MaxCacheLen: 1000 //最多缓存接口数 默认是1000条
})


/* config参数
  @showLoading  Boolean  请求是否显示loading
  @cache Boolean | Number 缓存设置，true为启用默认缓存时间， Number为自定义缓存时间
*/
const requestHttp = function (axiosParams: any, config: any) {
  const { showLoading,cache } = config
  let httpClient = cache ? cacheRequest : service // 判断缓存cache，为true时启用默认缓存时间，为Number时为自定义缓存时间单位秒
  let loading: any;
  if (showLoading) {
    loading = Toast.loading({
      message: '加载中...',
      forbidClick: true,
      duration:0
    })
  }
  return new Promise<void>((resolve, reject) => {
    httpClient({ ...axiosParams, config }).then((res:any) => {
      resolve(res)
    }).catch((err:any) => {

    }).finally(() => {
      loading && loading.clear()
    })
  })
}

export default requestHttp;
